package com.example.socket;

import android.content.Intent;
<<<<<<< HEAD
=======
<<<<<<< HEAD
=======
import android.content.SharedPreferences;
>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
<<<<<<< HEAD
import android.widget.Button;
import android.widget.ImageView;
=======
<<<<<<< HEAD
import android.widget.Button;
import android.widget.ImageView;
=======
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.bouncycastle.util.Arrays;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Base64;
import java.util.Optional;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends AppCompatActivity {
    private static final String tag = "MainActivity";
    private ImageView mImageView;
    private Socket mSocket;
    private ByteArrayOutputStream mOutputStream;
    private Bitmap mBitmap;
    private Handler mHandler;
    private Button click;

    private WebSocket webSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
<<<<<<< HEAD
=======
<<<<<<< HEAD
>>>>>>> 6a47a3d (最新提交)
        click = findViewById(R.id.click);
        click.setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, MainActivity2.class);
            startActivity(intent);
<<<<<<< HEAD
=======
=======
        saveUserInfo();
        click = findViewById(R.id.click);
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"开始链结",Toast.LENGTH_SHORT).show();
                connectWebsocketServer("ws://175.178.35.189:5765");
            }
>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)
        });
        mImageView = findViewById(R.id.imageView);
        mHandler = new Handler();
        // 创建一个线程用于连接服务器并接收图片数据
        new Thread(() -> {
            try {
                // 创建Socket连接
                mSocket = new Socket("175.178.35.189", 5765);
                // 获取输入流
                InputStream inputStream = mSocket.getInputStream();
                System.out.println("input");
                System.out.println(inputStream);
                // 创建一个字节数组输出流，用于存储图片数据
                mOutputStream = new ByteArrayOutputStream();
                byte[] data = new byte[1024];
                int len;
                while ((len = inputStream.read(data)) != -1) {
                    // 将读取到的数据写入到ByteArrayOutputStream中
                    mOutputStream.write(data, 0, len);
                    // 判断是否读取完一张图片
                    if (len < 1024) {
                        String str = mOutputStream.toString();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            byte[] imageData = Base64.getDecoder().decode(str);
                            mBitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

                            // 清空ByteArrayOutputStream
                            mOutputStream.reset();
                            // 在UI线程中更新UI
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // 将Bitmap类型的图片数据设置到ImageView上
                                    mImageView.setImageBitmap(mBitmap);
                                }
                            });
                        }
                    }
                }
                // 关闭输入流、ByteArrayOutputStream和Socket连接
                inputStream.close();
                mOutputStream.close();
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void connectWebsocketServer(String url) {
        OkHttpClient okHttpClient = GlobalOkhttpClient.okHttpClient;
        Request request = new Request.Builder()
                .url(GlobalOkhttpClient.baseUrl)
                .build();
        webSocket = okHttpClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.i(tag, "websocket已连接");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.i(tag, "websocket收到消息：" + text);
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.i(tag, "websocket收到二进制消息：" + bytes);
                byte[] byteArray = bytes.toByteArray();
                //等效于var bytes = new Uint8Array(msg.data);
                Integer[] ints = new Integer[byteArray.length];
                for (int i = 0; i < ints.length; i++) {
                    ints[i] = Byte.toUnsignedInt(byteArray[i]);
                }
                //等效于 string.fromCharCode(bytes[i])
<<<<<<< HEAD
                StringBuffer stringBuffer = new StringBuffer();
=======
<<<<<<< HEAD
                StringBuffer stringBuffer = new StringBuffer();
=======
                StringBuilder stringBuffer = new StringBuilder();

>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)
                for (Integer anInt : ints) {
                    char[] chars = Character.toChars(anInt);
                    stringBuffer.append(chars);
                }
<<<<<<< HEAD
=======
<<<<<<< HEAD
>>>>>>> 6a47a3d (最新提交)
                System.out.println(stringBuffer);
                //等效于img.src ='data:image/jpg;base64,' + window.btoa(binary);
                String encodeToString = Base64.getEncoder().encodeToString(stringBuffer.toString().getBytes());
                String bass64Str = "data:image/jpg;base64," + encodeToString;
                System.out.println(bass64Str);
                byte[] imageData = Base64.getDecoder().decode(bass64Str);
<<<<<<< HEAD
=======
=======
                //等效于img.src ='data:image/jpg;base64,' + window.btoa(binary);
                String encode = android.util.Base64.encodeToString(stringBuffer.toString().getBytes(), 0);
                //String encodeToString = Base64.getEncoder().encodeToString(stringBuffer.toString().getBytes());
                //String bass64Str = "data:image/jpg;base64," + encodeToString;
                //byte[] imageData = Base64.getDecoder().decode(encodeToString);
                byte[] imageData = android.util.Base64.decode(encode, 0);
>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                runOnUiThread(() -> Optional.ofNullable(mImageView).ifPresent(imageView -> imageView.setImageBitmap(bitmap)));
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                Log.i(tag, "websocket正在断开连接...");
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                Log.i(tag, "websocket已断开连接...");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                Log.i(tag, "websocket连接失败...原因：" + t.getMessage());
            }
        });
    }
<<<<<<< HEAD
=======
<<<<<<< HEAD
=======
    private void saveUserInfo(){
        SharedPreferences userInfo = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//获取Editor
        //得到Editor后，写入需要保存的数据
        editor.putString("username", "一只猫的涵养");
        editor.putInt("age", 20);
        editor.commit();//提交修改
    }
>>>>>>> 36b196d (最新提交)
>>>>>>> 6a47a3d (最新提交)
}